import {
    promptBox,
    toast
} from 'nc-lightapp-front';

import deepCopy from '../../public/functions/deep-copy';
import {openRevision} from "../actions/wpsinvoke.js";
import mockData from '../global/store/mock';

import {
    getBusinessInfo
} from 'nc-lightapp-front';

let tipsMap = {
    'add': 'hi6007-000035',
    'paste': 'hi6007-000171',
    'edit': 'hi6007-000036'
};

class Actions {
    constructor(comp) {
        this.comp = comp;
    }

    buttonsList = ['add', 'edit', 'delete', 'copy', 'paste', 'design', 'auth', 'preview', 'refresh', 'save', 'cancel', 'setting']

    // 处理预览的模版数据
    processPreViewTemplate = (data) => {

        const {meta, dispatch, gloRep, modal, editTable} = this.comp.props;
        let template = meta.getMeta();

        template['preview'] = {
            code: 'preview',
            moduletype: 'table',
            name: gloRep.language['hi6007-000210'], //'预览',
            items: []
        };

        data.map((item) => {
            template['preview'].items.push({
                attrcode: item.key,
                itemtype: 'input',
                label: item.name,
                visible: true
            });
        });

        meta.setMeta(template, () => {
            modal.show('preview');
            // editTable.setTableData('preview', {
            //     rows: deepCopy(mockData.previewMock)
            // }, false);
        });
    }

    // 预览
    preview = () => {
        const {dispatch, gloRep} = this.comp.props;
        const {language, selectedRow} = gloRep;

        dispatch({
            type: 'gloRep/preview'
        })
            .then((res) => {
                if (selectedRow && selectedRow.values['rpt_type'].value === '1') {
                    // location.port ? window.open("uclient://start/http://" + location.hostname + ":" + location.port + res.data) : window.open("uclient://start/http://" + location.hostname + res.data)
                    // toast()
                    toast({
                        color: 'warning',
                        content: language['hi6007-000363']
                    });
                } else {
                    this.processPreViewTemplate(res.data);
                }
            });
    }

    // 通过接口获取复制的数据
    getCopyData = () => {
        const {
            gloRep,
            dispatch
        } = this.comp.props;
        const {
            copyData
        } = gloRep;

        return dispatch({
            type: 'gloRep/getCopyData',
            payload: {
                pk_rpt_def: copyData.values['pk_rpt_def']
            }
        })
            .then((res) => {
                if (res.success) {
                    return res.data;
                }
            });
    }

    // 复制一行
    copyRow = () => {
        const {
            gloRep,
            dispatch
        } = this.comp.props;
        const {
            language,
            currentNode,
            selectedRow
        } = gloRep;

        dispatch({
            type: 'gloRep/update',
            payload: {
                copyTreeNode: currentNode.key,
                copyData: deepCopy(selectedRow)
            }
        });
        toast({
            color: 'success',
            content: language['hi6007-000173'] // '复制成功'
        });
    }

    // 保存左树节点修改/新增
    submitTreeNode = () => {
        const {
            dispatch,
            gloRep,
            syncTree,
            form
        } = this.comp.props;

        const {
            currentNodeOperatorType,
            currentNode,
            language
        } = gloRep;

        if (form.isCheckNow('folder')) {
            dispatch({
                type: 'gloRep/submitTreeNode',
                payload: {
                    formData: form.getAllFormValue('folder')
                }
            })
                .then((res) => {

                    if (res.success) {
                        toast({
                            color: 'success',
                            content: currentNodeOperatorType === 'add' ? language['hi6007-000035'] : language['hi6007-000036']//'新增成功' : '修改成功'
                        });
                        if (currentNodeOperatorType === 'add') {
                            if (Array.isArray(currentNode.children)) {
                                currentNode.children = currentNode.children.concat(res.data);
                            } else {
                                currentNode.children = res.data;
                            }
                            syncTree.setIconVisible('reportTree', [{
                                key: res.data[0].key,
                                value: {
                                    addIcon: true,
                                    delIcon: true,
                                    editIcon: true
                                }
                            }]);
                            // this.comp.forceUpdate();
                            // syncTree.addNodeSuccess('reportTree', res.data);
                        } else if (currentNodeOperatorType === 'change') {
                            currentNode.children && (res.data[0].children = currentNode.children);
                            Object.assign(currentNode, res.data[0]);
                            this.comp.forceUpdate();
                        }
                        this.toggleModal('treeNodeModalVisible', false)();
                    }
                });
        }
    }

    // 保存表格的修改
    saveTableChange = () => {
        const {
            editTable,
            gloRep,
            dispatch,
            syncTree
        } = this.comp.props;

        const {
            selectedRow,
            oldPageStatus,
            language
        } = gloRep;

        let hisList = [...oldPageStatus];
        let lastPageStatus = hisList.shift();

        let tableData = editTable.getAllData('rptlist');
        let editRow = tableData.rows[selectedRow.index]

        let checkRequired = editTable.checkRequired('rptlist', [editRow]);

        if (checkRequired) {
            dispatch({
                type: 'gloRep/saveTableChange',
                payload: {
                    tableData: {
                        ...tableData,
                        rows: [editRow]
                    }
                }
            })
                .then((res) => {
                    if (res.success) {
                        tableData[selectedRow.index] = res.data;
                        editTable.setTableData('rptlist', tableData, false);

                        this.setButtonStatus(lastPageStatus);
                        editTable.setStatus('rptlist', 'browse');
                        syncTree.setNodeDisable('reportTree', false);
                        editTable.focusRowByIndex('rptlist', selectedRow.index);

                        toast({
                            color: 'success',
                            content: language['hi6007-000036']
                        });
                        dispatch({
                            type: 'gloRep/update',
                            payload: {
                                pageStatus: lastPageStatus,
                                oldPageStatus: hisList
                            }
                        });
                    }
                });
        }

    }
    // 表格一行被点击
    rowClick = (props, tableId, record, index) => {

        const {
            gloRep,
            editTable
        } = this.comp.props;

        const {
            selectedRow,
            pageStatus
        } = gloRep;

        // 如果表格处于编辑态，点击某一行的时候，只让当前编辑的行高亮
        if (pageStatus === 'edit') {
            editTable.focusRowByIndex('rptlist', selectedRow.index);
        } else {
            console.log(record)
            if(record.values['rpt_type'].value === '1'){
                this.comp.props.button.setButtonDisabled(['preview'], true);
                this.comp.props.button.setButtonDisabled(['setting'], false);
            }else{
                this.comp.props.button.setButtonDisabled(['preview'], false);
                this.comp.props.button.setButtonDisabled(['setting'], true);
            }
            this.comp.props.dispatch({
                type: 'gloRep/update',
                payload: {
                    selectedRow: {
                        ...record,
                        index: index
                    }
                }
            });
        }
    }

    // 提交 新增  粘贴 表单 保存
    submitReport = () => {
        const {
            form,
            dispatch,
            editTable,
            gloRep: {
                buttonClick,
                language,
                selectedRow,
                currentNode,
                copyTreeNode
            },
            button
        } = this.comp.props;
        let formData = form.getAllFormValue('rptcard');
        let tableData = editTable.getAllRows('rptlist');
        if (formData.rows[0].values.rpt_code.value.length > 20) {
            toast({
                color: 'warning',
                content: language["hi6007-000366"] || '报表编码最大输入长度为20，请重新输入！'
            })
            return;
        }
        dispatch({
            type: 'gloRep/submitReport',
            payload: {
                formData: formData
            }
        })
            .then((res) => {
                if (res.success) {
                    this.toggleModal('createNewReportVisible', false)();
                    tableData = tableData.concat(res.data.rptlist.rows);
                    editTable.setTableData('rptlist', {rows: tableData});
                    if (!selectedRow.rowid) {
                        dispatch({
                            type: 'gloRep/update',
                            payload: {
                                selectedRow: {
                                    ...selectedRow,
                                    ...tableData[selectedRow.index]
                                }
                            }
                        });
                    }
                    editTable.focusRowByIndex('rptlist', selectedRow.index);
                    toast({
                        color: 'success',
                        content: language[tipsMap[buttonClick]]
                    });
                    this.setButtonStatus('tableWithData');
                }
            });
    }

    // 左树选择
    selectTree = (pk, node, status) => {
        if (node.code === 'root') {
            this.comp.props.dispatch({
                type: 'gloRep/update',
                payload: {
                    pk_folder: '',
                    currentNode: ''
                }
            });
            this.getTableData();
            return;
        }
        if (status) {
            this.comp.props.dispatch({
                type: 'gloRep/update',
                payload: {
                    pk_folder: node.nodeData.nodeValue.pk_rpt_def,
                    currentNode: node
                }
            });
            this.getTableData();
        } else {
            this.comp.props.dispatch({
                type: 'gloRep/update',
                payload: {
                    pk_folder: '',
                    currentNode: node
                }
            });
        }
    }

    // 表单编辑后
    onFormAfterChange = (rops, moduleId, key, valueObj, oldValue) => {
        const {gloRep, dispatch} = this.comp.props;
    
        if (moduleId === 'rptcard' && key === 'rpt_code') {
            let len = valueObj.value.length;
            if (len > 20) {
                toast({
                    color: 'warning',
                    content: gloRep.language["hi6007-000366"] || '报表编码最大输入长度为20，请重新输入！'
                })
                return;
            }
        }
        dispatch({
            type: 'gloRep/update',
            payload: {
                formValue: {
                    ...gloRep.formValue,
                    [key]: valueObj
                }
            }
        });
    }

    // 切换弹窗显示隐藏状态
    toggleModal = (fieldName, status) => {
        return () => {
            this.comp.props.dispatch({
                type: 'gloRep/update',
                payload: {
                    [fieldName]: status
                }
            });
        }
    }

    // 头部按钮点击事件处理
    headerButtonClick = (props, btnCode) => {

        const {
            gloRep,
            dispatch,
            editTable,
            form,
            meta,
            syncTree
        } = this.comp.props;

        const {
            pageStatus,
            oldPageStatus,
            language,
            selectedRow,
            pk_folder,
            tableData,
            currentNode,
            copyTreeNode,
            organizationTreeNode
        } = gloRep;

        const template = meta.getMeta();

        dispatch({
            type: 'gloRep/update',
            payload: {
                buttonClick: btnCode
            }
        });

        // 点击修改
        if (btnCode === 'edit') {
            dispatch({
                type: 'gloRep/checkTableEdit',
                payload: {
                    pk_rpt_def: selectedRow.values['pk_rpt_def'].value
                }
            })
                .then((res) => {
                    if (res.success) {
                        // 修改页面，先切换按钮状态
                        this.setButtonStatus('edit');

                        let allCols = template['rptlist'].items.map((item) => {
                            if (item.attrcode !== 'rpt_type') {
                                return item.attrcode;
                            }
                        });

                        // 禁用左树
                        syncTree.setNodeDisable('reportTree', true);
                        // 打开表格的编辑态
                        editTable.setStatus('rptlist', 'edit');

                        // 因为setStatus方法的回调函数报错了，所以权宜之计用了settimeout
                        setTimeout(() => {
                            // 禁用所有单元格的编辑
                            editTable.setColEditableByKey('rptlist', allCols, true);
                            // 取消禁用特定行的编辑态
                            editTable.setEditableRowByRowId('rptlist', selectedRow.rowid, true);
                            // 取消报表类型的可编辑性
                            editTable.setEditableRowKeyByRowId('rptlist', selectedRow.rowid, 'rpt_type', false);
                        }, 0);

                        dispatch({
                            type: 'gloRep/update',
                            payload: {
                                pageStatus: 'edit',
                                oldPageStatus: oldPageStatus.concat(pageStatus),
                                tableData: deepCopy(editTable.getAllData('rptlist'))
                            }
                        });
                    }
                });
        }
        // 取消编辑表格
        else if (btnCode === 'cancel') {
            let hisList = [...oldPageStatus];
            let lastPageStatus = hisList.shift();

            promptBox({
                color: "warning",
                title: language['hi6007-000196'],/* 国际化处理： 确认取消*/
                content: language['hi6007-000009'],/* 是否确认要取消 */
                beSureBtnClick: () => {
                    this.setButtonStatus(lastPageStatus);
                    editTable.setStatus('rptlist', 'browse');
                    editTable.setTableData('rptlist', tableData);
                    syncTree.setNodeDisable('reportTree', false);
                    editTable.focusRowByIndex('rptlist', selectedRow.index);
                    dispatch({
                        type: 'gloRep/update',
                        payload: {
                            pageStatus: lastPageStatus,
                            oldPageStatus: hisList
                        }
                    });
                }
            });
        }
        // 新增
        else if (btnCode === 'add') {
            if (!pk_folder) {
                toast({
                    color: 'warning',
                    content: language['hi6007-000209'] // '请先选中一个文件夹节点'
                });
            } else {
                dispatch({
                    type: 'gloRep/initAddModal'
                })
                    .then((res) => {
                        this.toggleModal('createNewReportVisible', true)();
                        form.setFormStatus('rptcard', 'edit');
                        form.setAllFormValue({
                            rptcard: res.data.rptcard
                        });
                        form.setFormItemsDisabled('rptcard', {
                            'rpt_type': false
                        });
                    });
            }
        }
        // 粘贴
        else if (btnCode === 'paste') {

            this.getCopyData()
                .then((data) => {
                    const copyData = data.rptcard;

                    let copyIndex = this.getCurrentCopyNodeIndex(gloRep.copyTreeNode);
                    let currentIndex = this.getCurrentCopyNodeIndex(currentNode.key);

                    if (!copyData) {
                        toast({
                            color: 'warning',
                            content: language['hi6007-000198'] //'请先复制一个报表'
                        });
                    } else if (copyIndex > currentIndex) {
                        toast({
                            color: 'warning',
                            content: language['hi6007-000247'] //'请选择本组织文件夹'
                        });
                    } else {
                        this.toggleModal('createNewReportVisible', true)();
                        form.setAllFormValue({
                            'rptcard': deepCopy(copyData)
                        });
                        form.setFormStatus('rptcard', 'edit');
                        form.setFormItemsDisabled('rptcard', {
                            'rpt_type': true
                        });
                        editTable.focusRowByIndex('rptlist', selectedRow.index);
                    }
                });
        }
        // 复制
        else if (btnCode === 'copy') {
            this.copyRow();
        }
        // 删除
        else if (btnCode === 'delete') {
            let selectedRow = gloRep.selectedRow;
            if (selectedRow.values) {
                promptBox({
                    color: 'warning',
                    title: language['hi6007-000200'], // 确认删除
                    content: language['hi6007-000202'], // 是否删除这个报表，
                    beSureBtnClick: () => {
                        if (selectedRow) {
                            dispatch({
                                type: 'gloRep/deleteReport'
                            })
                                .then((res) => {
                                    if (res.success) {
                                        toast({
                                            color: 'success',
                                            content: language['hi6007-000006'] // 删除成功
                                        });
                                        editTable.deleteTableRowsByIndex('rptlist', selectedRow.index, true);
                                        let tableData = editTable.getAllData('rptlist');
                                        if (tableData.rows.length > 0) {
                                            let newIndex = selectedRow.index > 0 ? selectedRow.index - 1 : selectedRow.index;
                                            editTable.focusRowByIndex('rptlist', newIndex);
                                            dispatch({
                                                type: 'gloRep/update',
                                                payload: {
                                                    selectedRow: {
                                                        ...tableData.rows[newIndex],
                                                        index: newIndex
                                                    },
                                                    tableData: deepCopy(tableData)
                                                }
                                            });

                                        } else {
                                            dispatch({
                                                type: 'gloRep/update',
                                                payload: {
                                                    selectedRow: {}
                                                }
                                            });
                                            this.setButtonStatus('initPage');
                                        }
                                    }
                                });
                        }
                    }
                });
            } else {
                toast({
                    color: 'warning',
                    content: language['hi6007-000058'] // 请先选择你要操作的数据
                });
            }
        }
        // 刷新
        else if (btnCode === 'refresh') {
            this.getTableData();
        }
        // 保存报表修改
        else if (btnCode === 'save') {
            this.saveTableChange();
        }
        // 设计
        else if (btnCode === 'design') {
            if (gloRep.selectedRow) {
                if (gloRep.selectedRow.values['rpt_type'].value === '1') {
                    let isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel");
                    if (isMac) {
                        toast({
                            color: 'warning',
                            content: language['hi6007-000363']|| '暂不支持MAC'
                        })
                        return false
                    }
                    if (!gloRep.isNeedWpsInterview) {
                        dispatch({
                            type: 'gloRep/update',
                            payload: {
                                wpsvisible: true
                            }
                        })
                    } else {
                        dispatch({
                            type: 'gloRep/wpsDesignData'
                        })
                            .then((res) => {
                                if (res.success) {
                                    console.log(res.data)
                                    let result = deepCopy(res.data)
                                    result.pk_rpt_def = gloRep.selectedRow.values['pk_rpt_def'].value
                                    openRevision(result)
                                    this.closeWpsModal()
                                }
                            });
                    }
                } else {
                    this.designAction.designReport();
                }

            } else {
                toast({
                    color: 'warning',
                    content: language['hi6007-000058'] // 请先选择你要操作的卡片报表
                });
            }
        }
            // else if(btnCode === 'designscript'){
            //     dispatch({
            //         type: 'gloRep/update',
            //         payload: {
            //             wpsvisible:true
            //         }
            //     })
            // }
        // 预览
        else if (btnCode === 'preview') {
            this.preview();
        }
        // 权限分配
        else if (btnCode === 'auth') {
            this.rightAssignment()
        }
        // 条件预置
        else if (btnCode === 'setting') {
            if (gloRep.selectedRow) {
                if (gloRep.selectedRow.values['rpt_type'].value === '1') {
                    this.toggleModal('preSettingVisible', true)();
                } else {
                    toast({
                        color: 'warning',
                        content: '条件预置仅支持卡片报表' || language['hi6007-000364'] // 条件预置仅支持卡片报表
                    });
                }
            } else {
                toast({
                    color: 'warning',
                    content: language['hi6007-000058'] // 请先选择你要操作的卡片报表
                });
            }
        }
    }

    closeWpsModal = () => {
        const {
            gloRep,
            dispatch,
        } = this.comp.props;
        dispatch({
            type: 'gloRep/update',
            payload: {
                wpsvisible: false
            }
        })
    }
    //当wps配置完成时打开wps
    confirmOpenWps = () => {
        const {
            gloRep,
            dispatch,
        } = this.comp.props;
        dispatch({
            type: 'gloRep/wpsDesignData'
        })
            .then((res) => {
                if (res.success) {
                    console.log(res.data)
                    let result = deepCopy(res.data)
                    result.pk_rpt_def = gloRep.selectedRow.values['pk_rpt_def'].value
                    openRevision(result)
                    this.closeWpsModal()
                }
            });
    }
    copySure = () => {
        const {
            language
        } = this.comp.props.gloRep;
        toast({
            color: 'success',
            content: language['hi6007-000173'] // '复制成功'
        });
    }
    // 获取传入的节点key的索引值，第2个是全局第3个是集团第4个是组织
    getCurrentCopyNodeIndex = (key) => {
        const treeData = deepCopy(this.comp.props.gloRep.treeData);

        let parentIndex = null;

        treeData[0].children.map((item, index) => {
            let nodeList = item.children || [];

            while (nodeList.length > 0) {
                let currentProcess = nodeList.shift();
                if (currentProcess.key === key) {
                    parentIndex = index;
                } else if (currentProcess.children) {
                    nodeList = nodeList.concat(currentProcess.children);
                }
            }
        });

        return parentIndex;
    }

    // 切换所有按钮的显示状态
    toggleAllButtonsVisible = (visible) => {
        let visibleValue = {};

        this.buttonsList.map((item) => {
            visibleValue[item] = visible
        });

        this.comp.props.button.setButtonsVisible(visibleValue);
    }

    // 切换所有按钮的禁用状态
    toggleAllButtonsDisable = (disable) => {
        const {selectedRow} =this.comp.props.gloRep
        let copyBtnList = JSON.parse(JSON.stringify(this.buttonsList))
        copyBtnList.shift()
        this.comp.props.button.setButtonDisabled(copyBtnList, disable);
        if (selectedRow && selectedRow.values['rpt_type'].value === '1'){
            this.comp.props.button.setButtonDisabled(['preview'], true);
        }else if(!selectedRow){
            this.comp.props.button.setButtonDisabled(['preview'], true);
        }
        
    }

    // 设置按钮的状态
    setButtonStatus = (pageStatus) => {

        if (pageStatus === 'initPage') {
            this.toggleAllButtonsDisable(true);
            this.toggleAllButtonsVisible(true);
            // preview
            this.comp.props.button.setButtonDisabled(['add', 'paste', 'refresh'], false);
            this.comp.props.button.setButtonsVisible({
                save: false,
                cancel: false
            });
        } else if (pageStatus === 'edit') {
            this.toggleAllButtonsDisable(false);
            this.toggleAllButtonsVisible(false);
            this.comp.props.button.setButtonsVisible({
                save: true,
                cancel: true
            });
        } else if (pageStatus === 'tableWithData') {
            this.toggleAllButtonsVisible(true);
            this.toggleAllButtonsDisable(false);
            this.comp.props.button.setButtonsVisible({
                save: false,
                cancel: false
            });
        }
    }

    // 编辑左树节点
    openEditTreeNodeModal = (clickType) => {
        return (node) => {
            const {
                dispatch,
                form
            } = this.comp.props;

            dispatch({
                type: 'gloRep/update',
                payload: {
                    currentNode: node,
                    currentNodeOperatorType: clickType,
                    pk_folder: node.nodeData.nodeValue.pk_rpt_def
                }
            });
            dispatch({
                type: 'gloRep/getEditTreeNodeModalTemplate',
                payload: {
                    clickType: clickType,
                    pk_folder: node.nodeData.nodeValue.pk_rpt_def,
                    currentNode: node,
                    currentNodeOperatorType: clickType
                }
            })
                .then((res) => {
                    this.toggleModal('treeNodeModalVisible', true)();
                    form.setFormStatus('folder', 'edit');
                    form.setAllFormValue({
                        folder: res.data.folder
                    });
                });
        }
    }

    // 删除报表目录
    deleteTreeNode = (node) => {
        const {gloRep, dispatch, syncTree} = this.comp.props;
        const {language} = gloRep;

        promptBox({
            color: 'warning',
            title: language['hi6007-000200'], // 确认删除，
            content: language['hi6007-000201'], // '是否删除这个报表目录'
            beSureBtnClick: () => {
                dispatch({
                    type: 'gloRep/deleteTreeNode',
                    payload: {
                        pk_folder: node.nodeData.nodeValue.pk_rpt_def,
                        currentNode: node,
                        currentNodeOperatorType: 'delete'
                    }
                })
                    .then((res) => {
                        if (res.success) {
                            syncTree.delNodeSuceess('reportTree', node.refpk);
                            toast({
                                color: 'success',
                                content: language['hi6007-000006'], // 删除成功
                            });
                        }
                    });
            }
        });
    }

    // 权限分配
    rightAssignment = () => {
        const {gloRep, dispatch, syncTree, openTo} = this.comp.props;
        const {language, selectedRow} = gloRep;
        // 遇到 复制出来的合同报表,这两个字段导致跳转后报错,后端说没用,直接置为空对象
        selectedRow['values'].obj_rpt_xml = {};
        selectedRow['values'].obj_rpt_def = {}
        dispatch({
            type: 'gloRep/rightAssignment'
        })
            .then((res) => {
                if (res.success) {
                    openTo('/hrhi/hrreportassignment/group/main/index.html', {
                        selectedRow: JSON.stringify(selectedRow),
                        appcode: '60070590'
                    })
                }
            });
    }

    // 获取页面高度
    getPageHeight() {
        if (window.getComputedStyle) {
            let height = window.getComputedStyle(document.getElementById('app')).height.replace('px', '');

            this.comp.props.dispatch({
                type: 'gloRep/update',
                payload: {
                    pageHeight: height
                }
            });
        }
    }
}

export default Actions;